<script setup>
import { addUserApi, getDetailsApi, modifyUserApi } from '@/api/user'
import { upload } from '@/api/file'
import { onMounted, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()

const userInfo = ref({
  nickname: '', // 用户名
  phone: '', // 手机号
  avatar: '',
  account: '',
  password: '',
  type: 1
})
const rules = {
  nickname: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 4, message: '姓名为1-4位' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      //   pattern 正则表达式
      pattern: /^1[3-9]\d{9}$/,
      message: '手机号格式不正确',
      trigger: 'blur'
    }
  ],
  account: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 4, max: 16, message: '账号长度为4-16位' }
  ],
  password: [
    { required: true, message: '请输密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码为6-16位' }
  ],
  avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }]
}
const setUserInfo = async (id) => {
  const res = await getDetailsApi(id)
  userInfo.value = res.data
}

// 新增/修改员工
const userForm = ref(null)
const saveData = () => {
  userForm.value.validate(async (isOk) => {
    if (isOk) {
      if (userInfo.value.id) {
        await modifyUserApi(userInfo.value)
        ElMessage.success('修改员工成功')
      } else {
        await addUserApi(userInfo.value)
        ElMessage.success('新增员工成功')
      }
      router.replace('/user')
    }
  })
}

// 图片格式校验
const beforeAvatarUpload = (rawFile) => {
  if (!['image/jpeg', 'image/jpg', 'image/png'].includes(rawFile.type)) {
    // eslint-disable-next-line no-undef
    ElMessage.error('仅支持上传jpeg、jpg、png格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    // eslint-disable-next-line no-undef
    ElMessage.error('请上传小于5M的图片')
    return false
  }
  return true
}

// 上传图片方法，返回图片url
const uploadAvatar = async (file) => {
  const formData = new FormData()
  formData.append('file', file.file)
  const res = await upload(formData)
  userInfo.value.avatar = res.data
}

onMounted(() => route.params.id && setUserInfo(route.params.id))
</script>

<template>
  <div class="dashboard-container">
    <div class="app-container">
      <div class="header-desc">
        <span>我的发布</span>
      </div>
      <div class="edit-form">
        <el-form
          ref="userForm"
          :model="userInfo"
          :rules="rules"
          label-width="160px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="账户类型" prop="type">
                <el-radio-group size="small" v-model="userInfo.type">
                  <el-radio :label="1"> 个人用户 </el-radio>
                  <el-radio :label="2"> 车商用户 </el-radio>
                  <el-radio :label="3"> 审核员 </el-radio>
                  <el-radio :label="4"> 系统管理员 </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 姓名 -->
          <el-row>
            <el-col :span="8">
              <el-form-item label="姓名" prop="nickname">
                <el-input v-model="userInfo.nickname" class="inputW" />
              </el-form-item>
            </el-col>
          </el-row>
          <!--手机 -->
          <el-row>
            <el-col :span="8">
              <el-form-item label="手机" prop="phone">
                <el-input v-model="userInfo.phone" class="inputW" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 账户 -->
          <el-row>
            <el-col :span="8">
              <el-form-item label="账号" prop="account">
                <el-input v-model="userInfo.account" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 密码 -->
          <el-row v-if="userInfo.id === undefined">
            <el-col :span="8">
              <el-form-item label="密码" prop="password">
                <el-input v-model="userInfo.password" type="password" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="position: relative; top: -5px; margin-bottom: 20px">
            <el-col :offset="3">
              <el-tag type="warning"
                >密码采用单向加密，不可找回，请自行记录</el-tag
              >
            </el-col>
          </el-row>
          <!-- 头像 -->
          <el-row>
            <el-form-item label="头像" prop="avatar">
              <el-upload
                class="avatar-uploader"
                action=""
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="uploadAvatar"
              >
                <img
                  v-if="userInfo.avatar"
                  :src="userInfo.avatar"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-row>
          <!-- 保存个人信息 -->
          <el-row type="flex">
            <el-form-item>
              <el-col>
                <el-button type="primary" @click="saveData">保存更新</el-button>
              </el-col>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.app-container {
  min-height: 620px;
  background-color: #fff;
}
.header-desc {
  border-bottom: 1px solid #ddd;
  padding: 15px 20px;
}
.edit-form {
  padding: 20px 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
}
</style>
